import React, {Component} from "react";
import {Link} from "react-router";
import {Table, Tree, Button, Form, Tabs, Input, DatePicker, Alert, Modal, Row, Col, Icon, message} from "antd";
import RoleForm from "./roleform";
import RoleUserForm from "./roleuserform";
import RoleFuncForm from "./rolefuncform";
import auth from "../../common/auth";
const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const TabPane = Tabs.TabPane;

let columns = [
    {
        title: '角色名称',
        dataIndex: 'rolename'
    }, {
        title: '描述',
        dataIndex: 'described'
    }, {
        title: '添加人',
        dataIndex: 'adduser'
    }
    , {
        title: '添加日期',
        dataIndex: 'addtime'
    }, {
        title: '最后修改人',
        dataIndex: 'modifyuser'
    }
    , {
        title: '最后修改日期',
        dataIndex: 'modifytime'
    }
];

export default class RoleList extends Component {
    state = {
        selectedKeys: [],
        selectedRowKeys: [],
        pagination: {
            showSizeChanger: false
        },
        autoExpandParent: true,
        record: {},
        modalVisible: false,
        title: '',
        option: '',
        params: {},
        startDate: null,
        endDate: null,
        rolename: '',
        authModal: false,
        tabsKey: '1',
    }

    handleTableChange(pagination, filters, sorter) {
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({pagination: pager});
        const params = {
            pageSize: pagination.pageSize,
            currentPage: pagination.current,
            sortField: sorter.field,
            sortOrder: sorter.order
        };
        for (let key in filters) {
            if (filters.hasOwnProperty(key)) {
                params[key] = filters[key];
            }
        }
        this.fetch(params);
    }

    handelOnRowClick(record, index) {
        this.setState({
            selectedRowKeys: [record.roleid],
            selectedRows: [record],
            record
        });
    }

    onSelectChange(selectedRowKeys) { //已选择行的key
        this.setState({selectedRowKeys});
        if(selectedRowKeys.length>0){
            this.setState({
                record: selectedRowKeys[0]
            });
        }
    }

    onSelectdTable(record, selected, selectedRows) { //当前选择的行
        console.log(record, selected, selectedRows);

        this.setState({
            record,
            selected,
            selectedRows
        });
    }

    handleChangeDate(date) {
        if (date.length > 0) {
            this.setState({
                startDate: date[0],
                endDate: date[1]
            });
        }
    }

    handleChangeKeyword(e) {
        this.setState({
            rolename: e.target.value
        })
    }

    /**
     * 表格表单查询
     * @return {[type]} [description]
     */
    handelBtnQuery() {
        let params = this.state.params;
        if (this.state.startDate != null) {
            params.startDate = this.state.startDate;
        } else {
            delete params.startDate;
        }
        if (this.state.endDate != null) {
            params.endDate = this.state.endDate;
        } else {
            delete params.endDate;
        }
        if (this.state.rolename != null && this.state.rolename != "") {
            params.rolename = this.state.rolename;
        } else {
            delete params.rolename;
        }
        this.fetch(params);
    }

    /**
     * 添加数据
     * @return {[type]} [description]
     */
    handleBtnAdd() {
        this.setState({
            modalVisible: true,
            title: '添加角色信息',
            record: {},
            option: 'add'
        })
    }

    /**
     * 修改数据
     * @return {[type]} [description]
     */
    handleBtnEdit() {
        if (this.state.selectedRows.length == 1) {
            this.setState({
                modalVisible: true,
                title: "编辑角色信息",
                option: 'update'
            });
            this.refs.role_form.getForm().resetFields();
        } else {
            message.info("只能修改一条数据！");
        }
    }

    /**
     * 删除数据
     * @return {[type]} [description]
     */
    handleBtnDelete() {
        let keyId = this.state.selectedRowKeys.join(",");
        let t = this
        confirm({
            title: '删除确认',
            content: '数据删除后无法恢复，确认要删除吗？',
            confirmLoading: this.state.delLoading,
            onOk(){
                t.setState({delLoading: true});
                let params = {
                    id: keyId
                };
                auth.fetch("/sys/role/delete", params, function (result) {
                    this.setState({delLoading: true});
                    if (result.result == '0') {
                        message.success(result.message);
                        this.fetch();
                    } else {
                        message.error(result.message, 10);
                    }
                }.bind(t));
            },
            onCancel() {
            }
        });
    }

    handleBtnView() {
        if (this.state.selectedRows.length == 1) {
            this.setState({
                modalVisible: true,
                title: "查看角色信息",
                option: 'view'
            });
        } else {
            message.info("只能修改一条数据！");
        }
    }

    /**
     * 保存数据
     * @return {[type]} [description]
     */
    handleOk() {
        //this.refs.article_form.handleSubmit();
        if (this.state.option == "view") {
            this.setState({
                modalVisible: false
            });
            return;
        }
        let myForm = this.refs.role_form.getForm();
        myForm.validateFields((errors, values) => {
            if (!!errors) {
                ('Errors in form!!!');
                return;
            }
            let form_value = myForm.getFieldsValue();
            let url = "/sys/role/save";
            if (this.state.option == "update") {
                url = "/sys/role/update";
            }
            auth.fetch(url, form_value, function (data) {
                this.setState({loading: false});
                if (data.result == '1') {
                    message.error(data.message, 10);
                    myForm.resetFields();
                } else {
                    message.success(data.message, 10);
                    this.setState({modalVisible: false});
                    myForm.resetFields();
                    //加载表格数据
                    this.fetch(this.state.params);
                }
            }.bind(this));
        });
    }

    fetch(params = {}) {
        this.setState({loading: true, params: params});
        auth.fetch('/sys/role/findlistByWhere', params, (res) => {
            if (res.result == "0") {
                this.setState({
                    loading: false,
                    tableData: res.data.list,
                    pagination: {
                        pageSize: res.data.pageSize,
                        current: res.data.pageNum,
                        total: res.data.total
                    }
                });
            } else {
                message.error(res.msg, 10);
            }
        });
    }

    handleCancel() {
        this.setState({modalVisible: false});
    }

    /**
     * 弹出授权窗口
     * @return {[type]} [description]
     */
    handleBtnAuth() {
        if (this.state.selectedRows.length == 1) {
            this.setState({
                authModal: true,
                record:this.state.selectedRows[0]
            });
        } else {
            message.info("只能选择一条角色授权！");
        }
    }

    handleAuthOk() {
        this.setState({authModal: false});
    }

    handleAuthCancel() {
        this.setState({authModal: false});
    }

    onTabsChange(tabsKey) {
        this.setState({tabsKey});
    }

    componentDidMount() { //初始化
        this.fetch();
    }

    render() {
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelectdTable.bind(this),
            onChange: this.onSelectChange.bind(this)
        };
        let btn_disabled = selectedRowKeys.length > 0 ? false : true;
        return (
            <div>
                <div className="form-query">
                    <Form inline>
                        <FormItem label="角色名称">
                            <Input placeholder="请输入搜索的角色名称" ref="rolename" size="default"
                                   onChange={this.handleChangeKeyword.bind(this)}/>
                        </FormItem>
                        <Button type="primary" onClick={this.handelBtnQuery.bind(this)}>查询</Button>
                    </Form>
                </div>
                <div style={{marginTop: 10}}>
                    <Button type="primary" className="btn-divider" onClick={this.handleBtnAdd.bind(this)}>新建</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnEdit.bind(this)}>编辑</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnView.bind(this)}>查看</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnDelete.bind(this)}>删除</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnAuth.bind(this)}>授权</Button>
                </div>
                <Table columns={columns} rowKey={record => record.roleid} rowSelection={rowSelection}
                       dataSource={this.state.tableData}
                       pagination={this.state.pagination} loading={this.state.loading}
                       onChange={this.handleTableChange.bind(this)}
                       onRowClick={this.handelOnRowClick.bind(this)}/>

                <Modal wrapClassName="vertical-center-modal" visible={this.state.modalVisible} width={600}
                       maskClosable={false} title={this.state.title} onOk={this.handleOk.bind(this)}
                       onCancel={this.handleCancel.bind(this)}>
                    <div className="modal_from">
                        <RoleForm ref="role_form" init={{option: this.state.option, data: this.state.record}}/>
                    </div>
                </Modal>

                <Modal wrapClassName="vertical-center-modal" visible={this.state.authModal} width={680}
                       maskClosable={false} title={'角色授权'} onOk={this.handleAuthOk.bind(this)}
                       onCancel={this.handleAuthCancel.bind(this)}>
                    <div className="modal_from">
                        <Alert message={`当前角色名称：${this.state.record.rolename}(角色代码：${this.state.record.roleid})`}
                               type="info" showIcon/>
                        <Tabs defaultActiveKey={this.state.tabsKey} onChange={this.onTabsChange.bind(this)}>
                            <TabPane tab={"用户权限"} key="1">
                                <RoleUserForm ref="role_user_form" init={{data: this.state.record}}/>
                            </TabPane>
                            <TabPane tab={"菜单权限"} key="3">
                                <RoleFuncForm ref="role_func_form" init={{data: this.state.record}}/>
                            </TabPane>
                        </Tabs>
                    </div>
                </Modal>

            </div>
        );
    }
};
